package cn.lj.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.lj.response.Const;
import cn.lj.response.Result;
import cn.lj.service.UserService;
import cn.lj.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;


/**
 * @file: AuthController
 * @version:
 * @Description: 代码目的，作用，如何工作
 * @author: 李津
 * @date: 2021-05-21 14:38
 * 本代码要注意的事项、备注事项等
 */

@RestController
@Api(value = "系统验证码模块",tags = "验证码接口")
public class AuthController {

    private final Producer producer;

    private final RedisUtil redisUtil;


    @Autowired
    public AuthController(Producer producer, RedisUtil redisUtil, UserService userService) {
        this.producer = producer;
        this.redisUtil = redisUtil;
    }

    /**
     * 生成验证码图片
     * @return
     * @throws IOException
     */
    @GetMapping("/captcha")
    @ApiOperation(value = "系统登录-图形验证码",notes = "查询验证码")
    public Result captcha() throws IOException{
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        // 为了测试
        key = "11111";
        code = "11111";

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        ImageIO.write(image,"jpg",outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

        Map<Object, Object> captcha = MapUtil.builder().
                put("randomKey", key).
                put("captchaImg", base64Img).build();
        return Result.ok().data(captcha);
    }


}
